import { useUserStore } from "@/store/user";
import type { User } from "@/store/user";

export const RECEIVE_MESSAGE = "receiveMessage";

// 监听receiveMessage
// 子应用触发type=receiveMessage的CustomEvent
export function listenReceiveMessage() {
  window.addEventListener("receiveMessage", function (e) {
    const { name, gender, age, phone } = (e as CustomEvent<User>).detail;
    const userStore = useUserStore();
    userStore.setUserInfo({ name, gender, age, phone });
  });
}

function createReceiveMessageEvent(message: Omit<Message, "from">) {
  return new CustomEvent(RECEIVE_MESSAGE, {
    detail: {
      ...message,
      from: "主应用",
    },
  });
}

export function dispatchReceiveMessageEvent(message: Omit<Message, "from">) {
  const event = createReceiveMessageEvent(message);
  window.dispatchEvent(event);
}
